package com.jr.webrtc.config;

import com.jr.webrtc.service.MyUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationManagerResolver;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception 
    {
        http
            .csrf().disable()
            .authorizeRequests()
                .requestMatchers("/ws/**").permitAll()
                .requestMatchers("/login").permitAll()
		        .requestMatchers("/clientlogin").permitAll()
                .requestMatchers("/createuser").permitAll()
                .requestMatchers("/createroom").permitAll()              
                .requestMatchers("/api/users").permitAll()
                .requestMatchers("/api/users/{id}").permitAll()
                .requestMatchers("/api/rooms").permitAll()
                .requestMatchers("/api/rooms/{id}").permitAll()
                .requestMatchers("/api/files/upload").permitAll()
                .requestMatchers("/api/files/download/{filename}").permitAll()
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .defaultSuccessUrl("/home", true)
                .permitAll()
            .and()
            .logout()
            .permitAll();

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
    
    public UserDetailsService userDetailsService(MyUserDetailsService myUserDetailsService) {
        return myUserDetailsService;
    }
}
